import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 这里用todoList管理所有项目的原因是:当用户想从"已完成"回档到"未完成"的时候，按找之前添加的待办项的顺序进行渲染
    // 管理所有的项目(包括未完成,已完成的)
    todoList: [],
    // 专门管理未完成项目 供"已完成列表"的渲染
    doneList: []
  },
  actions: {
    change_todo(context, data) {
      if (data.flag) {
        // 处理完成的
        context.commit('TO_DONELIST', data)
      } else {
        // 处理未完成的
        context.commit('TO_TODOLIST', data)
      }
    },
    delete_item(context, data) {
      if (data.finished) {
        // 如果要删除的是已完成项
        context.commit('DELETE_DONELIST', data)
      } else {
        // 删除的是未完成项
        context.commit('DELETE_TODOLIST', data)
      }
    },
    get_todoList(context) {
      let data = localStorage.getItem('todoList')
      if (data === null) return
      data = JSON.parse(data)
      console.log(data)
      context.commit('INIT_TODOLIST', data)
    }

  },
  mutations: {
    // 初始化项目
    INIT_TODOLIST(state, data) {
      state.todoList = data
      state.doneList = data.filter(item => item.finished)
    },
    // 添加todoItem
    ADD_TODO(state, todoObj) {
      state.todoList.push(todoObj)
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    },
    // 完成回档到未完成
    TO_TODOLIST(state, data) {
      state.todoList.some(item => {
        if (item.id === data.id) {
          item.finished = false
          return true
        }
      })
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
      // 查找要回退的哪项的下标
      const index = state.doneList.findIndex((item) => item.id === data.id)
      // 删除下标值为index的item
      state.doneList.splice(index, 1)
    },
    // 未完成->完成
    TO_DONELIST(state, data) {
      state.todoList.some(item => {
        if (item.id === data.id) {
          item.finished = true
          return true
        }
      })
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
      // 筛选出完成的哪一项追加到doneList 提供页面渲染
      state.doneList.push(...state.todoList.filter(item => item.id === data.id))
    },
    // 删除未完成项
    DELETE_TODOLIST(state, data) {
      // 从todoList中删除未完成项
      state.todoList = state.todoList.filter(item => item !== data)
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    },
    // 删除完成项
    DELETE_DONELIST(state, data) {
      // todoList和doneList都存储着完成项，因此都要删除
      state.todoList = state.todoList.filter(item => item !== data)
      state.doneList = state.doneList.filter(item => item !== data)
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    }

  },
  getters: {
    todoNum(state) {
      let total = 0
      state.todoList.forEach(item => {
        if (!item.finished) { total++ }
      })
      return total
    },
    doneNum(state) {
      let total = 0
      state.todoList.forEach(item => {
        if (item.finished) { total++ }
      })
      return total
    },
    total(state) {
      return state.todoList.length
    }
  }
})
